﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using CKS.EBE.API;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace CKS.EBE
{
    static class Helper
    {
        /// <summary>
        /// get list from the web
        /// (don't use for media list, linkbacks list (send and receive), themes list, binaries list)
        /// </summary>
        /// <param name="web">SPWeb where the list is stored</param>
        /// <param name="listFolderName">the rootfolder name of the list. e.g. beitraege (title would be Beiträge)</param>
        /// <returns>SPList</returns>
        internal static SPList GetListByFolderName(SPWeb web, string listFolderName)
        {
            try
            {
                // get list from url is faster. for a rootweb the ServerRelativeUrl is "/"
                string listUrl = web.ServerRelativeUrl == "/" ? string.Empty : web.ServerRelativeUrl;
                if (Localization.DocumentLibraries.Contains(listFolderName))
                {
                    // we have a document library
                    listUrl += string.Format("/{0}", listFolderName);
                }
                else
                {
                    // we have a list
                    listUrl += string.Format("/Lists/{0}", listFolderName);
                }
                SPList list = web.GetList(listUrl);
                return list;
            }
            catch (FileNotFoundException ex)
            {
                Trace.WriteLine("Could not get list from Web.GetList(): " + ex.Message);
                try
                {
                    SPList list = web.Lists[listFolderName];
                    return list;
                }
                catch (Exception e)
                {
                    Trace.WriteLine(string.Format("Error getting list '{0}': {1}", listFolderName, e.Message));
                    throw new ArgumentException(string.Format("Error getting list '{0}'", listFolderName));
                }
            }
        }

        /// <summary>
        /// get a list from the web
        /// </summary>
        /// <param name="web"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        internal static SPList GetList(SPWeb web, Localization.BlogList list)
        {
            string listName = Localization.GetListName(list, web.Language);
            SPList oList = GetListByFolderName(web, listName);
            return oList;
        }

        /// <summary>
        /// Get post item from post title (BlogTitleForUrl)
        /// </summary>
        /// <param name="urlTitle">test-ausgehender-link</param>
        /// <param name="oWeb"></param>
        /// <returns></returns>
        public static SPListItem GetPostFromUrlTitle(string urlTitle, SPWeb oWeb)
        {
            SPList oList = GetListByFolderName(oWeb, Localization.GetListName(Localization.BlogList.Posts, oWeb.Language));

            var query = new SPQuery
                            {
                                Query = string.Format("<Where><Eq><FieldRef Name='BlogTitleForUrl'/><Value Type='Text'>{0}</Value></Eq></Where>", urlTitle)
                            };

            SPListItemCollection items = oList.GetItems(query);
            return items.Count > 0 ? items[0] : null;
        }

        /// <summary>
        /// Get post item from friendly url
        /// </summary>
        /// <param name="url">http://www.hezser.de/archive/2009/04/23/welcome-to-your-blog.aspx</param>
        /// <param name="web"></param>
        /// <returns></returns>
        public static SPListItem GetPostFromUrl(string url, SPWeb web)
        {
            var re = new Regex("/.*/archive/(?<year>.*)/(?<month>.*)/(?<day>.*)/(?<title>.*).aspx");
            Match m = re.Match(url);

            string sTitle = m.Groups["title"].Value;
            SPListItem item = GetPostFromUrlTitle(sTitle, web);
            return item;
        }

        /// <summary>
        /// return the friendly url for a post
        /// </summary>
        /// <param name="webUrl"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        public static string GetFriendlyPostUrl(string webUrl, SPListItem item)
        {
            string postDate = ((DateTime)item["Created"]).ToString("yyyy-MM-dd HH:mm");
            string url = SPUrlUtility.CombineUrl(webUrl, "/archive/" + postDate.Substring(0, 4) + "/" + postDate.Substring(5, 2) + "/" + postDate.Substring(8, 2) + "/" + (string)item["BlogTitleForUrl"] + ".aspx");
            return url;
        }
    }
}
